"""
给定三个字符串 s1、s2、s3，请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/interleaving-string
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n = len(s1)
        m = len(s2)
        t = len(s3)
        if (t != n + m):
            return False
        f = [[False] * (m + 1) for _ in range(n + 1)]
        f[0][0] = True
        for i in range(1,n+1):
            f[i][0] = f[i-1][0] and s1[i-1] == s3[i-1]
        for j in range(1, m+1):
            f[0][j] = f[0][j-1] and s2[j-1] == s3[j-1]
        for i in range(1, n + 1):
            for j in range(1, m + 1):
                p = i + j - 1
                f[i][j] = (f[i-1][j] and s1[i-1] == s3[p]) or (f[i][j-1] and s2[j-1] == s3[p])
                f[i][j] = f[i][j] or (f[i][j-1] and s2[j-1] == s3[p:p+1])
        return f[n][m]
